/**
 * @author : bruce <bruceli1688@gmail.com>
 * @since : 2014-09-25
 * @version : 1.0
 * @description : new mobile
 */

define(function(require, exports, module){

    var Message, userInfo, roomName = 'masonsoft',
        imglazyload     = require('{component}imglazyload/zepto.imglazyload'),
        panel           = require('{component}panel/zepto.panel'),
        tpl             = require('{view}message.tpl'),
        tplN            = require('{view}userNav.tpl'),
        md5             = require('{component}md5/md5'),
        MiniIM          = require('candy');

    Message = Backbone.View.extend({

        el: '',

        template: _.template(tpl),
        templateN: _.template(tplN),

        StatusChange: {},
        ContactsHandler: {},
        MessageHandler: {},
        MessageErrorHandler: {},
        PresenceHandler: {},
        ArchiveHandler: {},
        OnlineUserHandler: {},
        UnreadHandler: {},
        TimeHandler: {},

        constructNewMessage: function(message_content, sender, msg_time) {
            var myDate = new Date(); 
            var message_obj = {"message" : message_content, "time" : (msg_time || myDate.getTime()), "sender" : sender};
            if (!msg_time) {
                message_obj.uniqueId = md5(message_content + myDate.getTime());
            }
            return message_obj;
        },
        UserInfoLoadCallback: function(callback_type) {
            var tthis = this;
            var obj = {};
            var _CALLBACK_TYPE = {
                NEW_PRIVATE_MESSAGE:        1,  // Get a new personal message
                NEW_CHATROOM_MESSAGE:       2,  // Get a new chat room message
                NEW_MEMBER_JOIN:            3,  // A new member join in the chatroom
                INIT_CHATROOM_HISTORY:      4,  // Get the last 100 chatroom history
                INIT_RECENT_CONTACTS:       5,  // Get recent contacts(included the sender from unread message)
                INIT_ONLINE_MEMBERS:        6,  // Get the online chatroom members
                OPEN_PRIVATE_CONVERSATION:  7   // Open new private chat conversation
            };

            obj.proccess = function(originalNamesArr) {
                switch(callback_type) {
                    case _CALLBACK_TYPE.NEW_PRIVATE_MESSAGE:
                        tthis.replaceUserAvatar('personal_chat', originalNamesArr);
                        break;
                    case _CALLBACK_TYPE.NEW_CHATROOM_MESSAGE:
                        tthis.replaceUserAvatar('chatroom', originalNamesArr);
                        break;
                    case _CALLBACK_TYPE.NEW_MEMBER_JOIN:
                        tthis.addUserToList('chatroom', originalNamesArr);
                        break;
                    case _CALLBACK_TYPE.INIT_CHATROOM_HISTORY:
                        tthis.replaceUserAvatar('chatroom', originalNamesArr);
                        tthis.initChatroomHistory = 1;
                        tthis.joinRoom();
                        break;
                    case _CALLBACK_TYPE.INIT_RECENT_CONTACTS:
                        tthis.addUserToList('personal_chat', originalNamesArr);
                        //Open conversation default if the "chat_with_user" exist.
                        if (chat_with_user) {
                            tthis.openPrivateConversation(chat_with_user);
                        }
                        //if (!difference_timestamp) {
                        //    MiniIM.Action.serverTime();
                        //}
                        break;
                    case _CALLBACK_TYPE.INIT_ONLINE_MEMBERS:
                        tthis.addUserToList('chatroom', originalNamesArr);
                        //tthis.checkChatroomHistory();
                        break;
                    case _CALLBACK_TYPE.OPEN_PRIVATE_CONVERSATION:
                        tthis.addUserToList('personal_chat', originalNamesArr);
                        tthis.showContactsList();
                        tthis.showConversation(originalNamesArr[0]);
                }
            };

            obj.exceptionProccess = function(originalNamesArr) {
                switch(callback_type) {
                    case _CALLBACK_TYPE.INIT_CHATROOM_HISTORY:
                        initChatroomHistory = 1;
                        joinRoom();
                        break;
                    case _CALLBACK_TYPE.INIT_RECENT_CONTACTS:
                        initContactsList = 1;
                        //if (!difference_timestamp) {
                        //    MiniIM.Action.serverTime();
                        //}
                        $('#contacts_list .user_items .loading').hide();
                        $('.none_message').show();
                        break;
                    case _CALLBACK_TYPE.INIT_ONLINE_MEMBERS:
                        initChatroomList = 1;
                        checkChatroomHistory();
                        break;
                }
            };

            return obj;
        },

        initialize: function () {
            var tthis = this;

            this.MessageHandler.proccess = function(obj, args) {
                console.log("Get New Message:"+JSON.stringify(args));
                tthis.addMessageToChatRoom(args);
            };
            this.MessageErrorHandler.proccess = function(obj, args) {
                console.log("Message Error:" + JSON.stringify(args));
            };
            this.PresenceHandler.proccess = function(obj, args) {
                console.log("Info: " + JSON.stringify(args));
                tthis.addUserToChatRoom(args);
            };
            this.ArchiveHandler.proccess = function(obj, args) {
                console.log("Archive: " + JSON.stringify(args));
                tthis.handleArchive(args);
            };
            this.ContactsHandler.proccess = function(obj, args) {
                console.log("Get Contacts:" + JSON.stringify(args));
            };
            this.UnreadHandler.proccess = function(obj, args) {
                console.log("Get Unread Message:"+JSON.stringify(args));
            };
            this.OnlineUserHandler.proccess = function(obj, args) {
                console.log("Get Online users:" + JSON.stringify(args));
            };
            this.TimeHandler.proccess = function(obj, args) {
                console.log("Time Handler: " + JSON.stringify(args));
            };
            this.StatusChange.proccess = function(obj, args) {
                switch(args.status) {
                    case Strophe.Status.CONNECTED:
                        MiniIM.log("CONNECTED");
                        break;
                    case Strophe.Status.ATTACHED:
                        MiniIM.log("Register all need handlers after login successfully");
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.MESSAGE, tthis.MessageHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ERROR, tthis.MessageErrorHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.PRESENCE, tthis.PresenceHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ARCHIVE, tthis.ArchiveHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.RECENT_CONTACTS, tthis.ContactsHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.UNREAD, tthis.UnreadHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.ONLINE_USERS, tthis.OnlineUserHandler);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.TIME, tthis.TimeHandler);
                        break;
                    case Strophe.Status.DISCONNECTED:
                        MiniIM.log("DISCONNECTED");
                        break;
                    case Strophe.Status.ERROR:
                        MiniIM.log("ERROR");
                        break;
                    case Strophe.Status.CONNFAIL:
                        MiniIM.log("CONNFAIL");
                }
            };
            this.initConnect();
        },

        render: function (obj) {
            if (!share.checkPermission(true)){return;};
            //$('#message').remove();
            if ($('#message').length < 1) {
                $('body').append(this.template(lang));
                if ($('#userNav').length < 1) { 
                    $('body').append(this.templateN(lang));
                    panel.info.state = 'show';
                    panel.init();
                    $('#userNav').imglazyload({startY : 0,endY: $(window).height(),sW:50,sH:50}); 
                }
                userInfo = share.userInfo();

                this.bindEvt();
            } else {
                $('#message').css('display','block');
            }
            this.panel(); 
        },

        bindEvt : function() {
            var tthis = this,dom = $('#message');
            dom.find('.left').on('tap',function(e){
                e.stopPropagation();
                if (panel.info.state == 'hidden') {
                    panel.show();
                } else {
                    panel.hidden(); 
                }
            }); 

            dom.on('tap',function(){
                if (panel.info.state == 'show' && $(window).width() < 640) {
                    panel.hidden();
                }
            });

            dom.find('#send_message').on('tap',function(e){
                e.stopPropagation();
                tthis.sendRoomMessage();
            }); 
        },
        initConnect: function() {
            var tthis = this;
            var obj = {
                url : seajs.data.vars.apiAccessUrl + 'bosh_client',
                type : 'POST',
                success : function(data) {
                    if (data.return_code == 0) {
                        MiniIM.init('/http-bind-new/?random=' + data.random, 'nudistfriends', data.session_id);
                        MiniIM.Handler.addHandler(MiniIM.Handler.KEYS.CONN_STATUS, tthis.StatusChange);
                        MiniIM.attach(data.jid, data.sid, data.rid);
                        //tthis.getContacts();
                        //tthis.getUnreadMessage();
                        tthis.joinRoom(roomName);
                        tthis.getOnlineChatroomUsers();
                        tthis.getArchive(roomName, 'chatroom');
                        //tthis.getArchive('lyle123456', 'personal_chat');
                    }
                }, 
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                }
            };

            $.ajax(share.ajaxControl(obj));
        },
        sendMessage: function(receiver) {
            var message, sender, senderId, receiverId;
            if (message) {
                var message_obj = this.constructNewMessage(message, sender);
                MiniIM.Action.sendMessage(receiver, message, null, {uniqueId: message_obj.uniqueId, senderId: senderId, receiverId: receiverId});
            }
        },
        sendRoomMessage: function() {
            var messageContent = $('#message_content').val(), sender = userInfo.username;
            if (messageContent) {
                var messageObj = this.constructNewMessage(messageContent, sender);
                MiniIM.Action.sendMessage(roomName, messageContent, 'groupchat', {uniqueId: messageObj.uniqueId});
            }
            $('#message_content').val('');
        },
        joinRoom: function(roomName) {
            MiniIM.Action.joinRoom(roomName);
        },
        getArchive: function(receiver, type, timepoint) {
            var receiver_id = '1697207';
            if (type == 'personal_chat') {
                MiniIM.Action.loadArchive(receiver, receiver_id, MiniIM.TYPE.PRIVATE, timepoint || null);
            } else if (type == 'chatroom') {
                MiniIM.Action.loadArchive(receiver, '', MiniIM.TYPE.ROOM, timepoint || null, 100);
            }
        },
        getContacts: function() {
            MiniIM.Action.loadRecentContacts();
        },
        getUnreadMessage: function() {
            MiniIM.Action.loadUnreadMessages();
        },
        removeConversation: function(username) {
            MiniIM.Action.removeArchive(username);
        },
        getOnlineChatroomUsers: function() {
            MiniIM.Action.loadOnlineUserList();
        },
        addUserToChatRoom: function(userInfos) {
            console.log('1111111111111111111111111111111111111',userInfos);
            if ($("#chat_room_list .chatroom_list_item_" + userInfos.name).length > 0) {
                return;
            }
            var userObj,
            obj = {
                url : seajs.data.vars.apiAccessUrl+'users_profile',
                type : 'POST',
                data : { users: userInfos.name },
                success : function(data) {
                    share.pageLoad(false,$('body'));
                    if (data.errcode == 121) {
                        alert(data.errmsg);
                    } else {
                        share.cacheUserInfo(userInfos.name, data);
                        //console.log(userObj);
                        // move it into tpl in future
                        var one_html = '<li><a class="chatroom_list_item_' + userInfos.name + '" data-username="' + userInfos.name + '">' + userInfos.name + '</a></li>';
                        if (userInfos.name == userInfo.username) {
                            $("#chat_room_list").prepend(one_html);
                        } else {
                            $("#chat_room_list").append(one_html);
                        }
                    }
                },
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                }
            };
            $.ajax(share.ajaxControl(obj));
        },
        addMessageToChatRoom: function(messages) {
            // move it into tpl in future
            var message_html = '<li>' + messages.sender + ': ' + messages.message + '</li>';

            $('#chat_room').append(message_html);
            $('#chat_room').scrollTop($('#chat_room')[0].scrollHeight);
        },
        addOneMessageToHistory: function(messages) {
            // move it into tpl in future
            var message_html = '<li>' + messages.sender + ': ' + messages.message + '</li>';

            $('#chat_room_' + messages.sender).append(message_html);
            $('#chat_room_' + messages.sender).scrollTop($('#chat_room_' + messages.sender)[0].scrollHeight);
        },
        isChatroomJid: function(jid) {
            var jid_name = jid.split('@conference.')[0];
            return (jid_name.toLowerCase() == roomName);
        },
        handleArchive: function(args) {
            var tthis = this;
            if (tthis.isChatroomJid(args.jid)) {
                $.each(args.messages, function(idx, message) {
                    var message_obj = tthis.constructNewMessage(message.message, message.sender, message.time);
                    tthis.addMessageToConversation('chatroom', message_obj);
                });
            }
        },
        addMessageToConversation: function(type, messageObj) {
            if (type == 'personal_chat') {
                this.addOneMessageToHistory(messageObj);
            } else if (type == 'chatroom') {
                this.addMessageToChatRoom(messageObj);
            }
        },
        panel: function() {
            panel.run({
                navName : 'message',
                rootDom : $('#message'),
                contentDom : $('#message').find('.body_all')
            });
        }

    });
    module.exports = Message;
})

